import {
  Button,
  Checkbox,
  Col,
  Form,
  FormInstance,
  Input,
  Modal,
  Row,
} from "antd";
import { useMount } from "ahooks";
import * as rpcApis from "@/ui/utils/rpc";
import { decrypt } from "@/ui/utils/crypto";

export function XHMLoginModal(props: {
  onLoginClick: () => void;
  form: FormInstance;
  logining?: boolean;
}) {
  const { form } = props;

  useMount(async () => {
    const config = await rpcApis.settings.getAll();
    let password = "";
    if (config.ASDF) {
      const [, pw, hi] = atob(config.ASDF).split(";");
      password = decrypt(pw, hi + config.XHM_USER_NAME);
    }

    const autoLogin = config.XHM_USER_AUTO_LOGIN === "true";
    const saveAuth = config.XHM_USER_SAVE_AUTH === "true";
    form.setFieldsValue({
      name: config.XHM_USER_NAME,
      password,
      autoLogin,
      saveAuth,
    });

    if (saveAuth && autoLogin) {
      props.onLoginClick();
    }
  });

  return (
    <Modal
      title={"请登录小红帽"}
      open={true}
      destroyOnClose={true}
      closable={false}
      maskClosable={false}
      keyboard={false}
      footer={
        <Button
          type="primary"
          onClick={props.onLoginClick}
          style={{ width: "100%" }}
          loading={props.logining}
        >
          登录
        </Button>
      }
      width={300}
    >
      <Form
        disabled={props.logining}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        form={props.form}
      >
        <Form.Item
          name={"name"}
          label={"用户名"}
          required={true}
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name={"password"}
          label={"密码"}
          required={true}
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input.Password />
        </Form.Item>

        <Row>
          <Col span={12}>
            <Form.Item
              style={{ margin: 0 }}
              labelCol={{ span: 20 }}
              wrapperCol={{ span: 4 }}
              name={"saveAuth"}
              label={"记住密码"}
              valuePropName={"checked"}
            >
              <Checkbox />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              style={{ margin: 0 }}
              labelCol={{ span: 20 }}
              wrapperCol={{ span: 4 }}
              name={"autoLogin"}
              label={"自动登录"}
              valuePropName={"checked"}
            >
              <Checkbox />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}
